package com.galaxy.service.config;


import java.net.InetAddress;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * ES配置类
 * @author caijinbang
 * @date 2018/8/30 21:54
 */
@Configuration
//加载 指定的配置，只支持properties
@PropertySource(value={"classpath:elasticsearch.properties"})
@Slf4j
public class ElasticSearchConfig {

  @Value("${es.hostName}")
  private String hostName;

  @Value("${es.transport}")
  private Integer transport;

  @Value("${es.cluster.name}")
  private String clusterName;

  /**
   * 初始化客户端配置信息
   * @return
   */
  @Bean
  public TransportClient transportClient() {
    log.info("initialize ElasticSearch Config");
    TransportClient client = null;
    try {
      TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(transport));
      // 配置信息
      Settings esSetting = Settings.builder().put("cluster.name",clusterName).build();
      //配置信息Settings自定义,下面设置为EMPTY
      client = new PreBuiltTransportClient(esSetting);
      client.addTransportAddresses(transportAddress);
    } catch (Exception e) {
      log.error("elasticsearch TransportClient create error!!!", e);
    }

    return client;
  }
}
